;$(function(){
	
	function UserDefinedController() {
		var grid = undefined, dialog = undefined;
		var uploadData = {};
		/**
		 * 状态格式化
		 */
		var statusFormatter = function(val, row, rowData) {
			if(val == 'on') {
				return TempoUtils.locale("mine.yifabu");
			} else if(val == 'off'){
				return TempoUtils.locale("mine.weifabu");
			} else {
				return TempoUtils.locale("mine.unkown");
			}
		}
		/**
		 * 节点分类国际化显示
		 */
		var subTypeFormatter = function(val, row, rowData) {
			try{
				return TempoUtils.locale('mine.' + val);
			}catch(e){}
			return val;
		}
		
		var action = function(val, row, rowData) {
			var ac = "<div class='user-defined-list-action' title=''>";
			   ac += "	<span class='user-defined-edit-action ui-icon tempo-ui-icon tempo-ui-icon-textseek' uda-id='$id' title='"+TempoUtils.locale("mine.publish-published-flow-grid-optview")+"'></span>";
			   ac += "	<span class='user-defined-delete-action ui-icon tempo-ui-icon tempo-ui-icon-delete' uda-id='$id' title='"+TempoUtils.locale("mine.mine_del")+"'></span>";
			   ac += "</div>";
			ac = ac.replace(/\$id/g, rowData.id)
			return ac;
		}
		
		var colName = [TempoUtils.locale("mine.classification"),TempoUtils.locale("mine.suanfamingcheng2"),TempoUtils.locale("mine.suanfajieshao"),TempoUtils.locale("mine.publish-mine-job-grid-col-status"),TempoUtils.locale("mine.publish-mine-job-grid-col-opt")];
		var colModel = [{name: "subType", sortable:false, formatter: subTypeFormatter},
		                {name: "name", sortable:false},
		                {name: "remark", sortable:false},
		                {name: "status", sortable:false, formatter: statusFormatter},
		                {name: "action", sortable:false, formatter: action}
		];
		
		/**
		 * 渲染页面布局
		 */
		var layout = function() {
			$('body').layout({
				north: {
					resizable : false,
					spacing_open: 0
				},
				center: {
					
				}
			});
			$('.user-defined-container').layout({
				north: {
					resizable : false,
					size : 50,
					spacing_open: 0
				},
				center: {
					
				}
			});
			$('.user-defined-list-container').layout({
				north: {
					resizable : false,
					size : 40,
					spacing_open: 0
				}
			});
		};
		
		/**
		 * 渲染工具条，添加新增按钮、模板下载等
		 */
		var toolbar = function() {
			$('.add-algorithm-button').button({
				click: function(e) {
					uploadData = {};
					openUploadDialog();
					return false;
				}
			});
			$('.back-forward-button').button({
				click: function(e) {
					window.location.href = forward.replace(/-/g, '&');
					return false;
				}
			});
		};
		/**
		 * 渲染列表，展示新增的算法节点信息
		 */
		var renderGrid = function() {
			grid = $('.user-defined-algorithm-list');
			var postdata = {};
			grid.datagrid({
				   fit: true, 
		           datatype: "json",
		           url: contextPath +　"/personal/listOwnAlgorithm",
		           colNames: colName,
		           colModel: colModel,
		           rowNum : 20,
		           rownumbers: true,
		           pagination: true,
		           multiselect: false,
		           shrinkToFit : true, 
		           onSelectRow : function(rowId){
		        	   
		           },
			       postData : postdata
			    });
		};
		
		/**
		 * 弹出上床算法界面对话框，选择要上传的算法包，上传提取算法信息并进行展示，确定无误后则进行发布申请
		 */
		var openUploadDialog= function(edit, id) {
			dialog = $('.user-defined-edit-dailog').dialog({
				modal : true,
				autoOpen : false,
				width : 460,
				height : 530,
				title : TempoUtils.locale("mine.zidingyisuanfafabushenqin"),
				resizable : false,
				close : function() {
					$('.user-defined-upload input').upload('destroy');
					$('.user-defined-upload').empty();
				},
				open : function() {
					uploadData = {};
					initForm();
					if(!edit) {
						$('.user-defined-upload-form').show();
						var upload = $('.user-defined-upload');
						var uploader = $('<input>').appendTo(upload);
						uploader.upload({
							text: TempoUtils.locale("mine.flow_choose"),
							name: 'userFile',
							width: 60,
							accept: '.jar',
							change: function(e, f) {
								uploadJar(e, f);
							}
						});
						//点击选择按钮时，默认禁用3秒
						var isUploadEnable = true;
						upload.find('input').on('click', function(e) {
							var e = $(this);
							var enable = true;
							if(isUploadEnable) {
								e.parents('.tempo-upload-container').addClass('tempo-upload-disable');
								setTimeout(function() {
									isUploadEnable = true
									e.parents('.tempo-upload-container').removeClass('tempo-upload-disable');
								}, 3000);
								isUploadEnable = false
							} else {
								enable = false;
							}
							return enable;
						});
						$('.user-defined-upload-form')
						.attr('enctype', 'multipart/form-data')
						.attr('method', 'post')
						.attr("action", contextPath + '/personal/uploadJar');;
						$('.user-defined-upload-name').validatebox({
							readonly: true,
							value: ''
						});
					} else {
						$('#user-defined-dialog-save-btn').remove();
						$('.user-defined-upload-form').hide();
						$.post(contextPath + '/personal/selectOne', {id: id}, function(data) {
							initForm(data, true);
						});
					}
				},
				buttons:[{
					text: TempoUtils.locale("mine.publish-dialog-sure"),
					id: 'user-defined-dialog-save-btn',
					click: function(){
						if(!$.isEmptyObject(uploadData)) saveUploadJar();
					}
				}]
			}).dialog("open");
			
		}
		/**
		 * 上传算法包
		 */
		var uploadJar = function(e, f) {
			$('.user-defined-upload-name').val(f.file.name);
			var process = $("<div/>").tempoprogressbar();
			$('.user-defined-upload-form').ajaxSubmit({
				dataType:'json',
				type : 'post',
				beforeSubmit:function(result){
					return true; 
				},
				success:function(data){
					if(data.error) {
						$('<div>').alert({msg: data.error});
					} else {
						initForm(data);
						uploadData = $.extend(uploadData, data);
					}
				},
				complete: function(){
					process.tempoprogressbar('destroy');
				},
				error:function( e ){
					process.tempoprogressbar("destroy");
					TempoUtils.uploadErrorHandler(e);
				}
			});
		}
		/**
		 * 初始化算法基本信息
		 */
		var initForm = function(data, full) {
			$('.user-defined-algorithm-info .text-value').empty();
			if(data) {
				var panel = $('.user-defined-algorithm-info');
				panel.find('.name').text(data.name || '');
				try{
					var v = TempoUtils.locale("mine." + data.subType);
					panel.find('.category').text(v);
				}catch(e){}
				panel.find('.lang').text(data.lang || '');
				panel.find('.username').text(data.userName || '');
				var d = DateUtils.formatDateTime(data.createDate);
				if(d || data.date) {
					panel.find('.date').parent().show();
					panel.find('.date').text(data.date || d).show();
				} else {
					panel.find('.date').parent().hide();
				}
				$('<textarea>').text(data.remark || '')
					.attr('readonly', true)
					.attr('title', data.remark || '')
					.appendTo(panel.find('.description'))
				var src = "";
				if(data.image) {
					src = contextPath + "/personal/image?src=" + data.image + "&baseResPath=" + data.baseResPath;
				} else if(data.icon) {
					src = "data:image/png;base64," + data.icon
				} else if(data.id) {
					src = contextPath + "/personal/image?id=" + data.id
				}
				$('<img>').attr('src', src).appendTo(panel.find('.image'));
				
			}
			if(full) {
				$('.user-defined-algorithm-info textarea').css('height', '150px');
			} else {
				$('.user-defined-algorithm-info textarea').css('height', '70px');
			}
		}
		/**
		 * 保存上传的算法包
		 */
		var saveUploadJar = function() {
			var process = $("<div/>").tempoprogressbar();
			$.post(contextPath + "/personal/saveOrUpdate", uploadData, function(data) {
				process.tempoprogressbar('destroy');
				if(data.status == "true") {
					dialog.dialog('close');
					$('<div>').alert({msg: TempoUtils.locale("mine.baocunchenggong")});
					grid.datagrid('reloadGrid');
				} else {
					$('<div>').alert({msg: data.error});
				}
			})
		}
		
		var bindEvent = function() {
			$('.user-defined-datagrid').on('click', '.user-defined-edit-action', function(e) {
				var ui = $(this);
				var id = ui.attr('uda-id');
				openUploadDialog(true, id);
			});
			
			$('.user-defined-datagrid').on('click', '.user-defined-delete-action', function(e) {
				var ui = $(this);
				var id = ui.attr('uda-id');
				$('<div>').confirm({
					msg: TempoUtils.locale("mine.publish-mine-job-grid-col-delete-confirm"),
					ok: function() {
						var process = $("<div/>").tempoprogressbar();
						$.post(contextPath + "/personal/remove?", {id: id}, function(d) {
							process.tempoprogressbar('destroy');
							if(d) {
								$('<div>').alert({msg: TempoUtils.locale("mine.shanchuchenggong")});
								grid.datagrid('reloadGrid');
							} else {
								$('<div>').alert({msg: TempoUtils.locale("mine.shanchushibaizidingyi")});
							}
						} );
					}
				});
			})
		}
		/**
		 * 页面初始化
		 */
		this.init = function() {
			layout();
			toolbar();
			renderGrid();
			bindEvent();
		}
	}
	
	new UserDefinedController().init();
});